package com.t2t.top.service.impl;

import com.t2t.top.dao.UserMapper;
import com.t2t.top.exception.ServiceException;
import com.t2t.top.model.po.User;
import com.t2t.top.model.po.UserExample;
import com.t2t.top.service.UserService;
import com.t2t.top.util.GsonUtils;
import com.t2t.top.log.LogTrace;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yangpengfei
 */
@Service
public class UserServiceImpl implements UserService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public Map myMap;

    @Autowired
    public UserMapper userMapper;

    @LogTrace
    public Integer add(User user) throws ServiceException {
        try {
            logger.info("添加用户{}", GsonUtils.toJson(user));
            if (user.getId() == null || user.getId() == 0) {
                UserExample e = new UserExample();
                e.createCriteria().andNameEqualTo(user.getName());

                User u = userMapper.selectByName(user.getName());
                if (u != null) {
                    throw new ServiceException("用户名已存在!");
                }
                if (StringUtils.isEmpty(user.getUserType())) {
                    user.setUserType("普通用户");
                }
                user.setCreateTime(new Date());
                return userMapper.insertSelective(user);
            }

            userMapper.updateByPrimaryKeySelective(user);
            return user.getId();
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    public void delete(User user) throws ServiceException {
        logger.info("删除用户" + GsonUtils.toJson(user));
        User u = (User) userMapper.selectByPrimaryKey(user.getId());
        if (u == null) {
            throw new ServiceException("该记录不存在!");
        }
        userMapper.deleteByPrimaryKey(user.getId());
    }

    @Override
    public Logger getLogger() {
        return this.logger;
    }

    public List query(User user) throws ServiceException {
        UserExample e = new UserExample();
        if (StringUtils.isNotEmpty(user.getName())) {
            e.createCriteria().andNameLike(user.getName());
        }
        logger.debug("入参:" + GsonUtils.toJson(user));
        List list = userMapper.selectByExample(e);
        logger.debug("出参:" + GsonUtils.toJson(list));
        return list;
    }

}
